import allure
import pytest
from pathlib import Path
from flaskr import create_app
from flaskr.db import get_db, init_db


@pytest.fixture(scope='session')
def data_sql():
    with allure.step('获取生成测试数据的SQL'):
        sql_file = Path(__file__).parent / 'data.sql'
        with open(sql_file, 'rb') as f:
            return f.read().decode('utf8')

@pytest.fixture
def app(tmp_path, data_sql):
    with allure.step('按配置创建flask的测试实例'):
        application = create_app({
            "TESTING": True,
            "DATABASE": tmp_path / 'flaskr.sqlite'
        })

    with allure.step('初始化测试数据'):
        with application.app_context():
            init_db()
            get_db().executescript(data_sql)

    return application

@pytest.fixture
def client(app):
    with allure.step('生成flask的测试客户端'):
        return app.test_client()

@pytest.fixture
def runner(app):
    with allure.step('生成flask的命令行测试终端'):
        return app.test_cli_runner()


class AuthActions:
    def __init__(self, client):
        self._client = client

    @allure.step('登录flaskr客户端')
    def login(self, username='test', password='test'):
        return self._client.post(
            '/auth/login',
            data={'username': username, 'password': password}
        )

    @allure.step('退出flaskr的登录')
    def logout(self):
        return self._client.get('/auth/logout')


@pytest.fixture
def auth(client):
    with allure.step('创建测试用户'):
        return AuthActions(client)
